package com.dan.controller;

import com.dan.pojo.Category;
import com.dan.pojo.Result;
import com.dan.service.impl.CategoryServiceImpl;
import com.dan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author danqihao
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryServiceImpl categoryServiceImpl;

    @PostMapping("/add")
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setCreateUser(userId);
        categoryServiceImpl.add(category);
        return Result.success();
    }

    @GetMapping("/findAll")
    public Result<List<Category>> findAll() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Category> category = categoryServiceImpl.findAll(userId);
        return Result.success(category);
    }

    @GetMapping("/findById")
    public Result<Category> findById(Integer id) {
        Category category = categoryServiceImpl.findById(id);
        return Result.success(category);
    }

    @PostMapping("/update")
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryServiceImpl.update(category);
        return Result.success();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        categoryServiceImpl.delete(id);
        return Result.success();
    }

}
